package main

import (
	"context"
	"fmt"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

type HelloReq struct {
	g.Meta `path:"/" method:"get" tags:"Test" summary:"Hello world test case"`
	Name   string `v:"required" dc:"姓名"`
	Age    int    `v:"required" dc:"年龄"`
}
type HelloRes struct {
	Content string `json:"content" dc:"返回结果"`
}
type Response struct {
	Message string      `json:"message" dc:"消息提示"`
	Data    interface{} `json:"data"    dc:"执行结果"`
}

type Hello struct{}

func (Hello) Say(ctx context.Context, req *HelloReq) (res *HelloRes, err error) {
	// r := g.RequestFromCtx(ctx)
	// r.Response.Writef(
	// 	"Hello %s! Your Age is %d",
	// 	req.Name,
	// 	req.Age,
	// )
	res = &HelloRes{
		Content: fmt.Sprintf(
			"Hello %s! Your Age is %d",
			req.Name,
			req.Age,
		),
	}
	return
}

func ErrorHandler(r *ghttp.Request) {
	// 执行路由函数
	r.Middleware.Next()
	// 判断是否产生错误
	// if err := r.GetError(); err != nil {
	// 	r.Response.Write("error occurs: ", err.Error())
	// 	return
	// }
	var (
		msg string
		res = r.GetHandlerResponse()
		err = r.GetError()
	)
	if err != nil {
		msg = err.Error()
	} else {
		msg = "OK"
	}
	r.Response.WriteJson(Response{
		Message: msg,
		Data:    res,
	})
}

func main() {
	s := g.Server()
	s.Group("/", func(group *ghttp.RouterGroup) {
		group.Middleware(ErrorHandler)
		group.Bind(
			new(Hello),
		)
	})

	// s.BindHandler("/", func(r *ghttp.Request) {
	// 	var req HelloReq
	// 	if err := r.Parse(&req); err != nil {
	// 		r.Response.Write(err.Error())
	// 		return
	// 	}
	// 	if req.Name == "" {
	// 		r.Response.Write("name should not be empty")
	// 		return
	// 	}
	// 	if req.Age <= 0 {
	// 		r.Response.Write("invalid age value")
	// 		return
	// 	}

	// 	r.Response.Writef(
	// 		"Hello %s! Your Age is %d",
	// 		req.Name,
	// 		req.Age,
	// 	)
	// })

	s.SetOpenApiPath("/api.json")
	s.SetSwaggerPath("/swagger")
	s.SetPort(8000)
	s.Run()
}
